package com.admin.oauth.util;

import com.admin.common.exception.BadRequestException;
import com.admin.core.entity.SysUser;
import com.admin.oauth.dto.LoginUserDto;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Set;

/**
 * 登录用户util
 *
 * @author sq-lan
 */
public class LoginUserUtil {

    public static String userName() {
        return user().getUsername();
    }

    public static int userId() {
        return user().getId();
    }

    public static boolean isAdmin() {
        return jwtUserDto().getUser().getIsAdmin();
    }

    /**
     * 用户信息
     *
     * @return {@link String}-
     */
    public static SysUser user() {
        return jwtUserDto().getUser();
    }

    public static Set<Integer> dataScopes() {
        return jwtUserDto().getDataScopes();
    }

    // public static List<AuthorityDto> authorities() {
    //     return jwtUserDto().getAuthorities();
    // }

    public static Set<String> permissions() {
        return jwtUserDto().getPermissions();
    }

    public static LoginUserDto jwtUserDto() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED.value(), "当前登录状态过期");
        }
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return ((LoginUserDto) userDetails);
        }
        throw new BadRequestException(HttpStatus.UNAUTHORIZED.value(), "找不到当前登录信息");
    }

}
